
import { Message } from 'element-ui'
import CryptoJS from 'crypto-js'
import util from "./kouzikeling"
import config from './config'

export function showMessage(msg, type) {
  let t = 'info'
  if (['info', 'success', 'warning', 'error'].includes(type)) {
    t = type
  }
  Message({
    dangerouslyUseHTMLString: true,
    showClose: true,
    message: msg,
    type: t,
    duration: 5000
  })
}
function hmacSha256(key, message) {
  const hmac = CryptoJS.HmacSHA256(message, key);
  return hmac.toString(CryptoJS.enc.Hex);
}

function sha256(message) {
  return CryptoJS.SHA256(message).toString(CryptoJS.enc.Hex);
}

function getSignatureKey(key, dateStamp, regionName, serviceName) {
  const kDate = CryptoJS.HmacSHA256(dateStamp, key);
  const kRegion = CryptoJS.HmacSHA256(regionName, kDate);
  const kService = CryptoJS.HmacSHA256(serviceName, kRegion);
  const kSigning = CryptoJS.HmacSHA256('request', kService);
  return kSigning;
}

function formatQuery(parameters) {
  return Object.keys(parameters)
    .sort()
    .map(key => `${key}=${parameters[key]}`)
    .join('&');
}

function getCurrentDateTime() {
  const now = new Date();
  return now.toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z';
}

function getDateStamp() {
  const now = new Date();
  return now.toISOString().split('T')[0].replace(/-/g, '');
}

function jimengAPI(queryParams,params) {

  const formattedQuery = util.formatQuery(queryParams);


  const formattedBody = JSON.stringify(params);
  const currentDate = util.getCurrentDateTime();
  const datestamp = util.getDateStamp();

  // Calculate payload hash
  const payloadHash = util.sha256(formattedBody);

  // Prepare canonical request
  const canonicalUri = '/';
  const canonicalQueryString = formattedQuery;
  const signedHeaders = 'content-type;host;x-content-sha256;x-date';
  const contentType = 'application/json';

  const canonicalHeaders = [
    `content-type:${contentType}`,
    `host:${new URL(config.jimeng.endpoint).hostname}`,
    `x-content-sha256:${payloadHash}`,
    `x-date:${currentDate}`
  ].join('\n') + '\n';

  const canonicalRequest = [
    'POST',
    canonicalUri,
    canonicalQueryString,
    canonicalHeaders,
    signedHeaders,
    payloadHash
  ].join('\n');

  // Prepare string to sign
  const algorithm = 'HMAC-SHA256';
  const credentialScope = `${datestamp}/${config.jimeng.region}/${config.jimeng.service}/request`;
  const hashedCanonicalRequest = util.sha256(canonicalRequest);

  const stringToSign = [
    algorithm,
    currentDate,
    credentialScope,
    hashedCanonicalRequest
  ].join('\n');

  // Calculate signature
  const signingKey = util.getSignatureKey(config.jimeng.secretKey, datestamp, config.jimeng.region, config.jimeng.service);
  const signature = util.hmacSha256(signingKey, stringToSign);

  // Prepare authorization header
  const authorizationHeader = [
    `${algorithm} Credential=${config.jimeng.accessKey}/${credentialScope}`,
    `SignedHeaders=${signedHeaders}`,
    `Signature=${signature}`
  ].join(', ');
  return {
    currentDate,
    authorizationHeader,
    payloadHash,
    contentType,
    canonicalQueryString
  }
}

export default {
  showMessage,
  getCurrentDateTime,
  hmacSha256,
  sha256,
  getSignatureKey,
  formatQuery,
  getDateStamp,
  jimengAPI
}